package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.DateConfig;
import com.gxuwz.stats.entity.*;
import com.gxuwz.stats.entity.AcademicPapers;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.AcademicPapersService;
import com.gxuwz.stats.service.AcademicPapersService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/academicPapers")
public class AcademicPapersController {

    @Autowired
    private AcademicPapersService academicPapersService;
    @Autowired
    private UserService userService;

    @GetMapping("/academicPapersList")
    public ResponseEntity<Map<String, Object>> academicPapersList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "4") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<AcademicPapers> page = new Page<>(currentPage, pageSize);
            QueryWrapper<AcademicPapers> queryWrapper = new QueryWrapper<>();

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }

            //            // 模糊查询条件 - 项目名称
            if (params.containsKey("paperTitle") && params.get("paperTitle") != null && !params.get("paperTitle").isEmpty()) {
                queryWrapper.like("paper_title", params.get("paperTitle"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("journalInfo") && params.get("journalInfo") != null && !params.get("journalInfo").isEmpty()) {
                queryWrapper.like("journal_info", params.get("journalInfo"));
            }

            // 模糊查询条件 - 项目类别
            if (params.containsKey("paperCategory") && params.get("paperCategory") != null && !params.get("paperCategory").isEmpty()) {
                queryWrapper.like("paper_category", params.get("paperCategory"));
            }

            // 精确查询条件 - 项目状态
            if (params.containsKey("paperPublishDate") && params.get("paperPublishDate") != null && !params.get("paperPublishDate").isEmpty()) {
                queryWrapper.eq("paper_publish_date", DateConfig.convertToLocalDate(params.get("paperPublishDate")));
            }

            if (params.containsKey("paperIssn") && params.get("paperIssn") != null && !params.get("paperIssn").isEmpty()) {
                queryWrapper.like("paper_issn", params.get("paperIssn"));
            }

            // 精确查询条件 - 项目提交状态
            if (params.containsKey("paperStatus") && params.get("paperStatus") != null && !params.get("paperStatus").isEmpty()) {
                queryWrapper.eq("paper_status", params.get("paperStatus"));
            }

            // 精确查询条件 - 项目审核状态
            if (params.containsKey("paperReviewStatus") && params.get("paperReviewStatus") != null && !params.get("paperReviewStatus").isEmpty()) {
                queryWrapper.eq("paper_review_status", params.get("paperReviewStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<AcademicPapers> resultPage = academicPapersService.getAPListWithUserInfo(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addAcademicPapers")
    public ResponseEntity<Map<String, Object>> addAcademicPapers(@RequestBody AcademicPapers academicPapers) {
        String username = academicPapers.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

        academicPapers.setPaperStatus("已提交");
        academicPapers.setPaperReviewStatus("未审核");
        academicPapers.setPaperSubmissionTime(LocalDateTime.now());

        // 判断该用户是否已经在 total_work 表中存在记录
//        QueryWrapper<AcademicPapers> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        int count = academicPapersService.count(queryWrapper);
//
//        if (count > 0) {
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "该用户已存在，不能重复新增");
//            return ResponseEntity.badRequest().body(response);
//        }

        // 设置 userId 并保存
        academicPapers.setUserId(userId);
        academicPapersService.save(academicPapers);

        String year = null;
        if (academicPapers.getPaperPublishDate() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                year = new SimpleDateFormat("yyyy").format(sdf.parse(academicPapers.getPaperPublishDate()));
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = academicPapers.getPaperPublishDate().substring(0, 4);
            }
        }
        if (year != null) {
            academicPapersService.updateTotalWorkPaperScore(userId, year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     */
    @DeleteMapping("/deleteAcademicPapers")
    public ResponseEntity<Map<String, Object>> deleteAcademicPapers(@RequestBody  List<Long> academicPapersIds) {
        // 1. 查出所有要删的数据
        List<AcademicPapers> toDelete = academicPapersService.listByIds(academicPapersIds);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (AcademicPapers ap : toDelete) {
            if (ap.getUserId() != null && ap.getPaperPublishDate() != null) {
                String year;
                try {
                    year = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("yyyy-MM").parse(ap.getPaperPublishDate()));
                } catch (Exception e) {
                    year = ap.getPaperPublishDate().substring(0, 4);
                }
                userYearSet.add(ap.getUserId() + "#" + year);
            }
        }

// 3. 删除
        academicPapersService.removeByIds(academicPapersIds);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            academicPapersService.updateTotalWorkPaperScore(userId, year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户
     */
    @PutMapping("/editAcademicPapers")
    public ResponseEntity<Map<String, Object>> editAcademicPapers(@RequestBody AcademicPapers academicPapers) {
        // 1. 获取前端传递的用户名
        String username = academicPapers.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            academicPapers.setUserId(user.getUserId());
        }

        academicPapersService.updateById(academicPapers);
        String year = null;
        if (academicPapers.getPaperPublishDate() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                year = new SimpleDateFormat("yyyy").format(sdf.parse(academicPapers.getPaperPublishDate()));
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = academicPapers.getPaperPublishDate().substring(0, 4);
            }
        }
        if (year != null) {
            academicPapersService.updateTotalWorkPaperScore(academicPapers.getUserId(), year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reviewAcademicPapers")
    public ResponseEntity<Map<String, Object>> reviewAcademicPapers(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long paperId = Long.valueOf(params.get("paperId").toString());
            String paperReviewStatus = params.get("paperReviewStatus").toString();
            String paperReviewResult = params.get("paperReviewResult") != null ? params.get("paperReviewResult").toString() : "";

            AcademicPapers paper = academicPapersService.getById(paperId);
            if (paper == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            paper.setPaperReviewStatus(paperReviewStatus);
            paper.setPaperReviewTime(LocalDateTime.now());
            paper.setPaperReviewResult(paperReviewResult);

            if ("审核通过".equals(paperReviewStatus)) {
                paper.setPaperReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(paperReviewStatus)) {
                paper.setPaperStatus("未提交");
            }

            academicPapersService.updateById(paper);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportAcademicPapers(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {
        System.out.println("year=="+year);

        // 3. 查询 AcademicPapers（可按年份筛选）
        QueryWrapper<AcademicPapers> queryWrapper = new QueryWrapper<>();
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("paper_publish_date", year.substring(0, 4));
        }

        // 只导出审核通过的数据
        queryWrapper.eq("paper_status", "已提交");

        List<AcademicPapers> list = academicPapersService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (AcademicPapers p : list) {
            p.setUsername(userIdNameMap.getOrDefault(p.getUserId(), ""));
        }
        // 统一格式化日期字段
//        DateFormatUtil.formatDateField(list, "paperPublishDate",
//                new String[]{"yyyy-MM-dd", "yyyy/MM/dd", "yyyy-MM", "yyyy年MM月dd日", "yyyy年MM月", "yyyy"},
//                "yyyy-MM-dd");

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 5. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "学术论文-" + now + ".xlsx";
//        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");


//        // 6. 设置响应头
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName);

        // 7. 导出
        ExcelExportUtil.export(response, list, AcademicPapers.class, "学术论文", fileName);
    }

}
